package com.hongyun.sdk.utils;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.hongyun.sdk.common.HongYunApi;
import com.hongyun.sdk.common.HongYunCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HongYunClient {

    private static final Logger log = LoggerFactory.getLogger(HongYunClient.class);
    private String channelId;
    private String url;

    private String customPrivateKey;
    private String customPublicKey;

    public HongYunClient(String channelId, String url, String customPrivateKey, String customPublicKey) {
        this.channelId = channelId;
        this.url = url;
        this.customPrivateKey = customPrivateKey;
        this.customPublicKey = customPublicKey;
    }

    Map<String, List<String>> headers = new HashMap<String, List<String>>();

    public Map<String, List<String>> getHeaders(String data) {
        headers.put("x-sign-type", Arrays.asList("RSA"));
        headers.put("x-sign", Arrays.asList(SignUtils.makeSign(data, customPrivateKey)));//签名
        headers.put("x-channel-id", Arrays.asList(channelId));
        return headers;
    }


    public <T> T request(HongYunApi api, Map<String, Object> param, Type type) {
        log.info("--------------------------------------------------------");
        log.info("鸿运SDK-请求地址:{}", api);
        log.info("鸿运SDK-请求参数:{}", param);
        HttpResponse response = HttpUtil.createPost(url.concat(api.getUrl())).
                header("x-sign-type", "RSA")
                .header("x-sign", SignUtils.makeSign(JSON.toJSONString(param), customPrivateKey))//签名
                .header("x-channel-id", channelId)
                .form(param).execute();
        log.info("鸿运SDK-响应:{}", response);
        if (response.isOk()) {
            return JSON.parseObject(response.body(), type);
        }
        log.info("--------------------------------------------------------");
        return JSON.parseObject(HongYunCommon.error(String.valueOf(response.getStatus()), "请求失败"), type);
    }
}
